package com.hzncc.scaffold.controller.Front.AliyunVod;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
import com.hzncc.scaffold.core.ResultT;
import com.hzncc.scaffold.entity.Vo.CommonDto;
import com.hzncc.scaffold.entity.Vo.GetPlayAuthVo;
import com.hzncc.scaffold.utils.AudioOrVideoCreateUpload;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import javax.xml.transform.Result;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: DrunkBear
 * @Date: 2022-06-18 15:14
 * @Description: null
 */
@RequestMapping("/aliyunVod")
@Api(tags = "前台接口-阿里云视频")
@RestController
public class AliyunVodController {

    @PostMapping("/getPlayInfo")
    @ApiOperation("获取视频播放地址")
    public ResultT getPlayInfo(String videoId) throws Exception {
        DefaultAcsClient client = initVodClient("LTAI4G78xLgxwq9JQssXnstF", "h9lmhLxsYOZp8chLl3p2ykakgJuZyX");
        GetPlayInfoResponse response = new GetPlayInfoResponse();
        ArrayList<GetPlayInfoResponse.PlayInfo> playInfoList = new ArrayList<>();
        try {
            response = getPlayInfo(client, videoId);
            playInfoList = (ArrayList<GetPlayInfoResponse.PlayInfo>) response.getPlayInfoList();
            //播放地址
            for (GetPlayInfoResponse.PlayInfo playInfo : playInfoList) {
                System.out.print("PlayInfo.PlayURL = " + playInfo.getPlayURL() + "\n");
            }
        } catch (Exception e) {
            System.out.print("ErrorMessage = " + e.getLocalizedMessage());
        }
        return  ResultT.success(playInfoList);
    }

    @PostMapping("/getPlayAuth")
    @ApiOperation("获取视频播放凭证")
    public ResultT<Map<String, Object>> getPlayAuth(@RequestBody CommonDto commonDto) throws ClientException {

        DefaultAcsClient client = AudioOrVideoCreateUpload.initVodClient("LTAI4G78xLgxwq9JQssXnstF", "h9lmhLxsYOZp8chLl3p2ykakgJuZyX");
        GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
        Map<String, Object> map = new HashMap<>();
        try {
            response = AudioOrVideoCreateUpload.getVideoPlayAuth(client,commonDto.getVideoId());

            map.put("PlayAuth",response.getPlayAuth());
            map.put("RequestId",response.getRequestId());
            GetVideoPlayAuthResponse.VideoMeta videoMeta = response.getVideoMeta();
            Map<String, Object> videoMetaMap = new HashMap<>();
            videoMetaMap.put("CoverURL",videoMeta.getCoverURL());
            videoMetaMap.put("Duration",videoMeta.getDuration());
            videoMetaMap.put("Status",videoMeta.getStatus());
            videoMetaMap.put("Title",videoMeta.getTitle());
            videoMetaMap.put("VideoId",videoMeta.getVideoId());
            map.put("VideoMeta",videoMetaMap);
        } catch (Exception e) {
            System.out.print("ErrorMessage = " + e.getLocalizedMessage());
        }
        return ResultT.success(map);
    }

    /**
     * 以下为调用示例
     */
    @PostMapping("/AddTranscodeTemplateGroup")
    @ApiOperation("视频转码")
    public void addTranscodeTemplateGroup() throws ClientException {
        DefaultAcsClient client = initVodClient("LTAI4G78xLgxwq9JQssXnstF", "h9lmhLxsYOZp8chLl3p2ykakgJuZyX");
        AddTranscodeTemplateGroupResponse response = new AddTranscodeTemplateGroupResponse();
        try {
            response = addTranscodeTemplateGroup(client);
            System.out.println("TranscodeTemplateGroupId = " + response.getTranscodeTemplateGroupId());
        } catch (Exception e) {
            System.out.println("ErrorMessage = " + e.getLocalizedMessage());
        }
        System.out.println("RequestId = " + response.getRequestId());
    }

    public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
        // 点播服务接入地域
        String regionId = "cn-shanghai";
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }

    /*获取播放地址函数*/
    public static GetPlayInfoResponse getPlayInfo(DefaultAcsClient client, String videoId) throws Exception {
        GetPlayInfoRequest request = new GetPlayInfoRequest();
        request.setVideoId(videoId);
        request.setResultType("Multiple");
        return client.getAcsResponse(request);
    }

    /*获取播放凭证函数*/
    public static GetVideoPlayAuthResponse getVideoPlayAuth(DefaultAcsClient client, String videoId) throws Exception {
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        request.setVideoId(videoId);
        return client.getAcsResponse(request);
    }

    /**
     * 添加转码模板组配置
     */
    public static AddTranscodeTemplateGroupResponse addTranscodeTemplateGroup(DefaultAcsClient client) throws Exception {
        AddTranscodeTemplateGroupRequest request = new AddTranscodeTemplateGroupRequest();
        //转码模板ID
        request.setName("6bc252cc98132595f0fa6c8e25fc63b6");
        request.setTranscodeTemplateList(buildTranscodeTemplateList().toJSONString());
        return client.getAcsResponse(request);
    }

    /**
     * 构建需要添加的转码模板配置数据
     *
     * @return
     */
    public static JSONArray buildTranscodeTemplateList() {
        JSONObject transcodeTemplate = new JSONObject();
        //模板名称
        transcodeTemplate.put("TemplateName", "testtemplate");

        //清晰度
        transcodeTemplate.put("Definition", "LD");

        //视频流转码配置
        JSONObject video = new JSONObject();
        video.put("Width", 640);
        video.put("Bitrate", 400);
        video.put("Fps", 25);
        video.put("Remove", false);
        video.put("Codec", "H.264");
        video.put("Gop", "250");
        transcodeTemplate.put("Video", video);

        //音频流转码配置
        JSONObject audio = new JSONObject();
        audio.put("Codec", "AAC");
        audio.put("Bitrate", "64");
        audio.put("Channels", "2");
        audio.put("Samplerate", "32000");
        transcodeTemplate.put("Audio", audio);

        //封装容器
        JSONObject container = new JSONObject();
        container.put("Format", "mp4");
        transcodeTemplate.put("Container", container);

        //条件转码配置
        JSONObject transconfig = new JSONObject();
        transconfig.put("IsCheckReso", false);
        transconfig.put("IsCheckResoFail", false);
        transconfig.put("IsCheckVideoBitrate", false);
        transconfig.put("IsCheckVideoBitrateFail", false);
        transconfig.put("IsCheckAudioBitrate", false);
        transconfig.put("IsCheckAudioBitrateFail", false);
        transcodeTemplate.put("TransConfig", transconfig);

        //加密配置(只支持m3u8)
        //JSONObject encryptSetting = new JSONObject();
        //encryptSetting.put("EncryptType", "Private");
        //transcodeTemplate.put("EncryptSetting", encryptSetting);

        //水印ID(多水印关联)
        JSONArray watermarkIdList = new JSONArray();
        watermarkIdList.add("263261bdc1ff65782f8995c6dd22a16a");
        //USER_DEFAULT_WATERMARK 代表默认水印ID
        watermarkIdList.add("USER_DEFAULT_WATERMARK");
        transcodeTemplate.put("WatermarkIds", watermarkIdList);

        JSONArray transcodeTemplateList = new JSONArray();
        transcodeTemplateList.add(transcodeTemplate);
        return transcodeTemplateList;
    }


}
